﻿#include "WlsSpyPanel.h"
#include "FusionSpyResource.h"
#include <wx/sstream.h>
#include <wx/xml/xml.h>
#include <wx/stdpaths.h>

#define SOCKET_ID 0x139
#define ID_TIMER 2048

#if 1
/*
wxString wlsstatus_list_value[] = {
	wxT("Wls Version:"),
	wxT("System Boot:"),
	wxT("Last Update:"),
	wxT("Servers Num:"),
	wxT("Domain Name:"),
	wxT("AdminServer:"),
	wxT("Admin   JDK:"),
	wxT("Admin    OS:"),
	wxT("Productions:"),
	wxT("Agent  Ver:"),
	wxT("")
};
*/
wxString wlsstatus_list_value[] = {
	wxT("Wls Version:"),
	wxT("System Boot:"),
	wxT("Last Update:"),
	wxT("Servers Num:"),
	wxT("Domain Name:"),
	wxT("Admin   Svr:"),
	wxT("Admin    OS:"),
	wxT("CPU    Idle:"),
	wxT("MEM    Free:"),
	wxT("Agent   Ver:"),
	wxT("")
};

wxString wlsserver_list_column[] = {
	wxT("Server Name"),
	wxT("URL"),
	wxT("Port"),
	wxT("Health"),
	wxT("State" ),
//	wxT("OS Type"),
//	wxT("OS Version"),	
	wxT("")
};

wxString jvm_list_column[] = {
	wxT("Server Name"),
	wxT("JVM Vendor"),
	wxT("JVM Version"),
	wxT("Free Heap"),
	wxT("Current Heap"),
	wxT("HeapSizeMax"),
	wxT("FreePercent"),
	wxT("")
};

wxString thread_list_column[] = {
	wxT("Server Name"),
	wxT("Total Count"),
	wxT("Idle Count"),
	wxT("Throughput"),
	wxT("QueueLength"),
	wxT("")
};


wxString jdbc_list_column[] = {
	wxT("Server Name"),
	wxT("JDBC Name"),
	wxT("Active Current"),
	wxT("Active High"),
	wxT("CurrCapacity"),
//	wxT("DeploymentState"),
	wxT("Leak Count"),
	wxT("State"),
	wxT("")
};

//Below are Runtime Info to get from WebLogic
wxString JVMRunTime[] = {
	wxT("OSName"),
	wxT("OSVersion"),
	wxT("JavaVersion"),
	wxT("JavaVendor"),
	wxT("JavaVMVendor"),
	wxT("HeapFreeCurrent"),
	wxT("HeapSizeCurrent"),
	wxT("HeapSizeMax"),
	wxT("HeapFreePercent"),
	wxT("")
};

wxString ServerRunTime[] = {
	wxT("ActivationTime"),
	wxT("HealthState"),
	wxT("State"),
	wxT("Name"),
	wxT("OpenSocketsCurrentCount"),
	wxT("WeblogicVersion"),
	wxT("ListenAddress"),
	wxT("ListenPort"),
	wxT("")
};

wxString ThreadRunTimeV9[] = {
	wxT("ExecuteThreadIdleCount"),
	wxT("CompletedRequestCount"),
	wxT("ExecuteThreadTotalCount"),
	wxT("PendingUserRequestCount"),
	wxT("QueueLength"),
	wxT("StandbyThreadCount"),
	wxT("Throughput"),
	wxT("")
};

wxString ThreadRunTimeV8[] = {
	wxT("Name"),
	wxT("ServicedRequestTotalCount"),
	wxT("ExecuteThreadTotalCount"),
	wxT("ExecuteThreadCurrentIdleCount"),
	wxT("PendingRequestCurrentCount"),
	wxT("")
};

wxString JDBCRunTime[] = {
	wxT("ActiveConnectionsCurrentCount"),
	wxT("ActiveConnectionsHighCount"),
	wxT("CurrCapacity"),
//	wxT("DeploymentState"),
//	wxT("FailedReserveRequestCount"),
	wxT("LeakedConnectionCount"),
	wxT("Name"),
	wxT("State"),
	wxT("")
};

/*
enum {
	DISABLE=0,	ENABLE,	COLOR, JDBCLOW,JVMLOW, THREADLOW, SVRDIED
};
*/
#define DISABLE  0      ///< 
#define ENABLE 0x0001
#define JDBCLOW  0x0002  ///< 
#define JVMLOW  0x0004  ///< 
#define THREADLOW  0x0008  ///< 
#define SVRDIED  0x0010  ///< 
#define COLOR  0x0020  ///< 

#endif

BEGIN_EVENT_TABLE(WlsSpyPanel, WlsPanel)
	EVT_TIMER(ID_TIMER, WlsSpyPanel::OnTimer)
	EVT_SOCKET(SOCKET_ID, WlsSpyPanel::OnSocketEvent)
END_EVENT_TABLE()

WlsSpyPanel::WlsSpyPanel( wxWindow* parent )
:
WlsPanel( parent )
{
	m_IsStart = false;
	m_timer.SetOwner(this,ID_TIMER);
	m_tuxsite.InitSocket(*this, SOCKET_ID);

	InitControl();

	alarmaction.InitAlarm();

}
int WlsSpyPanel::GetLicenseType()
{
	if( wlsinitbuf.AgentVersion.Contains(wxT("TRIAL")) ) {
		return -1;
	}

	return 1;
}
void WlsSpyPanel::StartMonitor()
{
	int ret = 0;
	int port = 0;
	wxString value;
	wxInt32 interval = 0;
	wxChar debugmsg[1024];
	wxString xmlbuf;

	memset( debugmsg, 0, sizeof(wxChar) );

	m_site.SitePort.ToULong((unsigned long*)&port);
	ret = m_tuxsite.Connect(m_site.SiteIP,port);
	if ( ret == -1 ) {
		sprintf( debugmsg, wxT("Connect to Host[%s: %d] Failed!"), m_site.SiteIP, port );
		wxMessageBox( debugmsg );
		return;
	}
	ret = m_tuxsite.HandShake() ;
	if ( ret == -1 ) {
		wxMessageBox( wxT("HandShake to Host Failed!") );
		return;
	}

	value = m_txtInterval->GetValue();
	interval = atoi( value.c_str() ) * 1000;
	if ( interval <  15000 ) {
		wxMessageBox( wxT("Interval can not set below 15!") );
		return;
	}

	m_timer.Start(interval);

	m_IsStart = true;	
	m_btnControl->SetLabel(wxT("Stop"));
	m_txtInterval->Enable(false);

	for( int i = 0; i< 9; i++ ) {
		m_lstStatus->SetItem(i, 1, wxT("") );
	}

	m_nreccount = 0;

	xmlbuf = XmlInit();
	m_rcvdata = m_tuxsite.ActVsAgent(GETINITDATA, xmlbuf);

	SvrDataParser();
	UpdateControl();

	return;
}
void WlsSpyPanel::StopMonitor()
{
	m_timer.Stop();
	m_tuxsite.Close();
	m_IsStart = false;
	m_btnControl->SetLabel(wxT("Start"));
	m_txtInterval->Enable(true);
	
	return;
}

void WlsSpyPanel::OnControl( wxCommandEvent& event )
{

	if(  m_IsStart == false ) {
		StartMonitor();
	} else {
		if( wxMessageBox(wxT("Stop a running WebLogic site monitor?"),wxT("Confirm"),wxYES_NO|wxICON_QUESTION) == wxYES ) {
			StopMonitor();	
		}
	}

}
void WlsSpyPanel::OnBtnLogClear( wxCommandEvent& event )
{
	m_txtSystem->Clear();
}

void WlsSpyPanel::SetSite( Site site)
{
	m_site = site;

	// Find the site's Alarm
	wxString StdDataDir = wxStandardPaths::Get().GetDataDir();
	wxString dbname = StdDataDir + wxT("\\") + m_site.DatabaseFile;

	dbWrapper.DBOpen( dbname, WLSTABLE );

	// Find the site's Alarm
	int n = dbWrapper.WlsAlarmListQuery( m_site.SiteName );
	if( n == 0 ){ // New Alarm Setting 
	} else {
		m_wlsalarm = dbWrapper.getWlsAlarm();
	}

}

void WlsSpyPanel::OnTimer(wxTimerEvent& event)
{
	WlsPanelThread* pThread = new WlsPanelThread((WlsSpyPanel*)this);        
	pThread->Create();
	pThread->Run();

} 
void WlsSpyPanel::OnSocketEvent( wxSocketEvent& event)
{
	int flag = m_tuxsite.OnEvent( event );
	if( flag == wxSOCKET_LOST ) { //Detect Connection is broken.
			wxString sysinfo = wxT("Connection to agent is broken!");
			wxDateTime now = wxDateTime::Now();
			wxString crttime = now.Format(wxT("[%y-%m-%d %X]: [WARN]: "),wxDateTime::A_WST);
			m_txtSystem->AppendText(crttime+sysinfo);
			m_timer.Stop();
			m_tuxsite.Close();
			m_IsStart = false;
			m_btnControl->SetLabel(wxT("Start"));
			m_txtInterval->Enable(true);
	}
}

void WlsSpyPanel::OnAlarmSet(wxCommandEvent& event )
{
	int n = 0;
	FusionSpyWlsAlarmDlg* alarmSet = new FusionSpyWlsAlarmDlg( this );

	alarmSet->SetWlsAlarm( m_wlsalarm );

	if( alarmSet->ShowModal() != IDOK ) return;
	m_wlsalarm = alarmSet->GetWlsAlarm();

	m_wlsalarm.SiteName = m_site.SiteName;
	dbWrapper.WlsAlarmUpdate(m_wlsalarm);

}

wxString WlsSpyPanel::XmlInit()
{
	wxString XmlClause;
	wxString Clause;
	wxString XmlVersion = wxT("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");

	wxString XMLDomainBase = wxT("<Domain name=\"localDomain\" ");
	wxString XMLDomain = XMLDomainBase + wxT("adminAddress=\"") + m_site.SiteIP + wxT("\" ") + wxT("adminPort=\"") + m_site.WlsAdminURL + wxT("\" ")
         + wxT(" principal=\"") + m_site.SiteAuth + wxT("\" ") + wxT("password=\"") + m_site.SitePwd + wxT("\"/>");

	wxString XMLJVMRuntime = wxT("<MBean mBeanType=\"runtime\" name=\"JVMRuntime\">");
	wxString XMLServerRuntime = wxT("<MBean mBeanType=\"runtime\" name=\"ServerRuntime\">");
	wxString XMLThreadRuntimeV8  = wxT("<MBean mBeanType=\"runtime\" name=\"ExecuteQueueRuntime\">");
	wxString XMLThreadRuntimeV9  = wxT("<MBean mBeanType=\"runtime\" name=\"ThreadPoolRuntime\">");
	wxString XMLJDBCRuntimeV8 = wxT("<MBean mBeanType=\"runtime\" name=\"JDBCConnectionPoolRuntime\">");
	wxString XMLJDBCRuntimeV9 = wxT("<MBean mBeanType=\"runtime\" name=\"JDBCServiceRuntime.JDBCDataSourceRuntimeMBeans\">");

	XmlClause += XmlVersion;
	XmlClause += wxT("<wlsagent>") ;
	//XmlClause += XmlHead;
	XmlClause += XMLDomain;

	XmlClause += XMLJVMRuntime;
	// JVM List Init
	for ( int i = 0; !JVMRunTime[i].IsEmpty(); i ++ ) {
		Clause += wxString::Format(wxT("<attribute>%s</attribute>"),JVMRunTime[i] ); 
	}
	XmlClause += Clause;
	XmlClause += wxT("</MBean>");

	XmlClause += XMLServerRuntime;

	// Server List Init
	Clause.Empty();
	for ( int i = 0; !ServerRunTime[i].IsEmpty(); i ++ ) {
		Clause += wxString::Format(wxT("<attribute>%s</attribute>"),ServerRunTime[i] ); 
	}
	XmlClause += Clause;
	XmlClause += wxT("</MBean>");

	// Thread List Init
	Clause.Empty();
	if( m_site.WlsVer.Contains(wxT("V8")) ) {
		XmlClause += XMLThreadRuntimeV8;
		for ( int i = 0; !ThreadRunTimeV8[i].IsEmpty(); i ++ ) {
			Clause += wxString::Format(wxT("<attribute>%s</attribute>"),ThreadRunTimeV8[i] ); 
		}
	}else {
		XmlClause += XMLThreadRuntimeV9;
		for ( int i = 0; !ThreadRunTimeV9[i].IsEmpty(); i ++ ) {
			Clause += wxString::Format(wxT("<attribute>%s</attribute>"),ThreadRunTimeV9[i] ); 
		}
	}
	XmlClause += Clause;
	XmlClause += wxT("</MBean>");

	// JDBC List Init
	if( m_site.WlsVer.Contains(wxT("V8")) )
		XmlClause += XMLJDBCRuntimeV8;
	else
		XmlClause += XMLJDBCRuntimeV9;

	Clause.Empty();
	for ( int i = 0; !JDBCRunTime[i].IsEmpty(); i ++ ) {
		Clause += wxString::Format(wxT("<attribute>%s</attribute>"),JDBCRunTime[i] ); 
	}
	XmlClause += Clause;
	XmlClause += wxT("</MBean>");


	XmlClause += wxT("</wlsagent>");
	return XmlClause;

}

int WlsSpyPanel::InitControl()
{
	wxInt16 SvrCount = 0;
	long tmp = 0;

	wxListItem itemCol;

	// Server List Init
	for ( int i = 0; !wlsserver_list_column[i].IsEmpty(); i ++ ) {
		itemCol.SetText(wlsserver_list_column[i]);
		m_lstSvrInfo->InsertColumn(i, itemCol);
	};
	// JVM List Init
	for ( int i = 0; !jvm_list_column[i].IsEmpty(); i ++ ) {
		itemCol.SetText(jvm_list_column[i]);
		m_lstJvmInfo->InsertColumn(i, itemCol);
	};

	// Thread List Init
	for ( int i = 0; !thread_list_column[i].IsEmpty(); i ++ ) {
		itemCol.SetText(thread_list_column[i]);
		m_lstThdInfo->InsertColumn(i, itemCol);
	};

	// JDBC List Init
	for ( int i = 0; !jdbc_list_column[i].IsEmpty(); i ++ ) {
		itemCol.SetText(jdbc_list_column[i]);
		m_lstJDBCInfo->InsertColumn(i, itemCol);
	};

	// Status List Init
	itemCol.SetText(wxT("Statu"));
	m_lstStatus->InsertColumn(0, itemCol);

	itemCol.SetText(wxT("Values"));
	m_lstStatus->InsertColumn(1, itemCol);

	for ( int i = 0; !wlsstatus_list_value[i].IsEmpty(); i ++ ) {
		m_lstStatus->InsertItem( i, wlsstatus_list_value[i] );
	};

	for( int i = 0; i< m_lstStatus->GetColumnCount(); i ++ )
		m_lstStatus->SetColumnWidth(i, wxLIST_AUTOSIZE_USEHEADER);

	return 1;

}

void WlsSpyPanel::UpdateControl()
{
	double size = 0;
	wxInt32 count = 0;
	wxInt32 svrcount = 0;
	wxString SqlClause, sizevalue;

	wxDateTime now = wxDateTime::Now();
	wxString currenttime = now.Format(wxT("%Y-%m-%d %X"),wxDateTime::A_WST);

	svrcount = (wxInt16)wlssvrarray.GetCount();

	m_lstSvrInfo->Hide();
	m_lstSvrInfo->DeleteAllItems();

	for( int i = 0; i < svrcount ; i ++ ) {
		WebLogicServer wlssvr;
		wlssvr = wlssvrarray.Item(i);

		long tmp = m_lstSvrInfo->InsertItem( i, wlssvr.ServerName );
		m_lstSvrInfo->SetItemData( tmp, i );
		if( wlssvr.Flag & COLOR ){
			m_lstSvrInfo->SetItemTextColour(i, *wxRED);
		}
		m_lstSvrInfo->SetItem(i, 1, wlssvr.URL);
		m_lstSvrInfo->SetItem(i, 2, wlssvr.PORT);
		m_lstSvrInfo->SetItem(i, 3, wlssvr.HealthState);
		m_lstSvrInfo->SetItem(i, 4, wlssvr.State);

	}

	for( int i = 0; i< m_lstSvrInfo->GetColumnCount(); i ++ )
		m_lstSvrInfo->SetColumnWidth(i, wxLIST_AUTOSIZE_USEHEADER);
	wxMilliSleep(100);
	m_lstSvrInfo->Show();

	count = (wxInt16)wlsjvmarray.GetCount();
	m_lstJvmInfo->Hide();
	m_lstJvmInfo->DeleteAllItems();
	for( int i = 0; i < count ; i ++ ) {
		WebLogicJVM wlsjvm;
		wlsjvm = wlsjvmarray.Item(i);
		long tmp = m_lstJvmInfo->InsertItem( i, wlsjvm.ServerName );
		m_lstJvmInfo->SetItemData( tmp, i );
	
		if( wlsjvm.Flag & COLOR ){
			m_lstJvmInfo->SetItemTextColour(i, *wxRED);
		}

		m_lstJvmInfo->SetItem(i, 1, wlsjvm.Vendor);
		m_lstJvmInfo->SetItem(i, 2, wlsjvm.Version);

		wlsjvm.FreeHeap.ToDouble(&size); size = size /1024 /1024;
		sizevalue = wxString::Format( "%4.2fM", size );
		m_lstJvmInfo->SetItem(i, 3, sizevalue);
		
		wlsjvm.CurrHeap.ToDouble(&size); size = size /1024 /1024;
		sizevalue = wxString::Format( "%4.2fM", size );
		m_lstJvmInfo->SetItem(i, 4, sizevalue);

		wlsjvm.HeapSizeMax.ToDouble(&size); size = size /1024 /1024;
		sizevalue= wxString::Format( "%4.2fM", size );
		m_lstJvmInfo->SetItem(i, 5, sizevalue);

		m_lstJvmInfo->SetItem(i, 6, wlsjvm.FreePercent);

	}
	for( int i = 0; i< m_lstJvmInfo->GetColumnCount(); i ++ )
		m_lstJvmInfo->SetColumnWidth(i, wxLIST_AUTOSIZE_USEHEADER);
	wxMilliSleep(100);
	m_lstJvmInfo->Show();


	count = (wxInt16)wlsthdarray.GetCount();
	m_lstThdInfo->Hide();
	m_lstThdInfo->DeleteAllItems();

	for( int i = 0; i < count ; i ++ ) {
		WebLogicThread wlsthd;
		wlsthd = wlsthdarray.Item(i);
		long tmp = m_lstThdInfo->InsertItem( i, wlsthd.ServerName );
		m_lstThdInfo->SetItemData( tmp, i );

		if( wlsthd.Flag & COLOR ){
			m_lstThdInfo->SetItemTextColour(i, *wxRED);
		}

		m_lstThdInfo->SetItem(i, 1, wlsthd.TotalCount);
		m_lstThdInfo->SetItem(i, 2, wlsthd.IdleCount);
		m_lstThdInfo->SetItem(i, 3, wlsthd.ThroughPut);
		m_lstThdInfo->SetItem(i, 4, wlsthd.QueueLength);

	}
	for( int i = 0; i< m_lstThdInfo->GetColumnCount(); i ++ )
		m_lstThdInfo->SetColumnWidth(i, wxLIST_AUTOSIZE_USEHEADER);
	wxMilliSleep(100);
	m_lstThdInfo->Show();

	count = (wxInt16)wlsjdbcarray.GetCount();
	m_lstJDBCInfo->Hide();
	m_lstJDBCInfo->DeleteAllItems();

	for( int i = 0; i < count ; i ++ ) {
		WebLogicJDBC wlsjdbc;
		wlsjdbc = wlsjdbcarray.Item(i);
		long tmp = m_lstJDBCInfo->InsertItem( i, wlsjdbc.ServerName );
		m_lstJDBCInfo->SetItemData( tmp, i );
		
		if( wlsjdbc.Flag & COLOR ){
			m_lstJDBCInfo->SetItemTextColour(i, *wxRED);
		}

		m_lstJDBCInfo->SetItem(i, 1, wlsjdbc.Name);
		m_lstJDBCInfo->SetItem(i, 2, wlsjdbc.ActiveConnectionsCurrentCount);
		m_lstJDBCInfo->SetItem(i, 3, wlsjdbc.ActiveConnectionsHighCount);
		m_lstJDBCInfo->SetItem(i, 4, wlsjdbc.CurrCapacity);
	//	m_lstJDBCInfo->SetItem(i, 5, wlsjdbc.DeploymentState);
		m_lstJDBCInfo->SetItem(i, 5, wlsjdbc.LeakedConnectionCount);
		m_lstJDBCInfo->SetItem(i, 6, wlsjdbc.State);

	}
	for( int i = 0; i< m_lstJDBCInfo->GetColumnCount(); i ++ )
		m_lstJDBCInfo->SetColumnWidth(i, wxLIST_AUTOSIZE_USEHEADER);
	wxMilliSleep(100);
	m_lstJDBCInfo->Show();

	//Update the system information.

	//Update WebLogic Version
	m_lstStatus->SetItem(0, 1, wlsinitbuf.DomainVersion );
	m_lstStatus->SetItemTextColour(0, *wxRED );

	//Update WebLogic System Boot information
	m_lstStatus->SetItem(1, 1, wlsinitbuf.Activationtime );
	m_lstStatus->SetItemTextColour(1, *wxRED );

	//Update the last update Time.
	m_lstStatus->SetItem(2, 1, m_lastupdate);

	//Update the Running information.
	
	m_lstStatus->SetItem(3, 1, wxString::Format(wxT("Total: %s - Running: %d"), wlsinitbuf.ServerNum, svrcount) );
	m_lstStatus->SetItem(4, 1, wlsinitbuf.Name);
	m_lstStatus->SetItem(5, 1, wlsinitbuf.AdminServerName);
	
/*
	wxT("Admin  Svr:"),
	wxT("Admin   OS:"),
	wxT("CPU   Idle:"),
	wxT("MEM   Free:"),
	wxT("Agent  Ver:"),
*/
	//Update the system information.
/*
	m_lstStatus->SetItem(6, 1, wlsinitbuf.JDKVendor + wxT(" ") + wlsinitbuf.JDKVersion);
	m_lstStatus->SetItem(7, 1, wlsinitbuf.OSName + wxT(" ") +  wlsinitbuf.OSVersion);
	m_lstStatus->SetItem(8, 1, wlsinitbuf.ProductionModeEnabled );
	m_lstStatus->SetItem(9, 1, wlsinitbuf.AgentVersion );
*/
	m_lstStatus->SetItem(6, 1, wlsinitbuf.OSName + wxT(" ") +  wlsinitbuf.OSVersion);
	m_lstStatus->SetItem(7, 1, wlssys.IdleCPU );
	m_lstStatus->SetItem(8, 1, wlssys.FreeMem );
	m_lstStatus->SetItem(9, 1, wlsinitbuf.AgentVersion );

	for( int i = 0; i< m_lstStatus->GetColumnCount(); i ++ )
		m_lstStatus->SetColumnWidth(i, wxLIST_AUTOSIZE );
	//m_lstStatus->Show();

	m_wlsresource.sysresource.RecTime = currenttime;
	m_wlsresource.WlsSvrNum = wlsinitbuf.ServerNum;
	m_wlsresource.WlsRunSvr = wxString::Format(wxT("%d"), svrcount);// Need to update
	m_wlsresource.sysresource.CPUIdle = wlssys.IdleCPU;

	int offset = wlssys.FreeMem.First('M');
	m_wlsresource.sysresource.MemFree = wlssys.FreeMem.Left(offset);

	UpdateLogWindow( 1 );
	
	// Save Queue/Server/Client Infor into database.
	if( m_chkSaveDB->IsChecked() ) {
		if( GetLicenseType() < 1  && m_nreccount > 10) {
			wxMessageBox( TRIAL_LICENSE_WARN );
			m_chkSaveDB->SetValue(false);
		} else {
			if( m_nreccount == 0 ){//Insert Record Vestige
				m_sysreclist.AgentVer = wlsinitbuf.AgentVersion;
				m_sysreclist.OSType = wlsinitbuf.OSVersion;
				m_sysreclist.ProductVer = wlsinitbuf.DomainVersion;
				m_sysreclist.RecTime = currenttime;
				m_sysreclist.SystemBoot =  wlsinitbuf.Activationtime;
				dbWrapper.SysRecListInsert( m_sysreclist );
			}
			if( !m_wlsresource.sysresource.CPUIdle.IsEmpty() ) // if not null save in db
				dbWrapper.WlsResourceInsert( m_wlsresource );
/*
			if( !m_tuxresource.TuxRunSvr.IsEmpty() ) //if not null save in db
				dbWrapper.TuxResourceInsert( m_tuxresource );
*/
			dbWrapper.WlsSvrLstSave( wlssvrarray, currenttime );
			dbWrapper.WlsJvmLstSave( wlsjvmarray, currenttime );
			dbWrapper.WlsThdLstSave( wlsthdarray, currenttime );
			dbWrapper.WlsJDBCLstSave( wlsjdbcarray, currenttime );
		}
		m_nreccount ++; if( m_nreccount > 65535) m_nreccount = 1;// reset nRecCount;
	} else {
		m_nreccount = 0;
	}
}

void WlsSpyPanel::UpdateLogWindow(int type )
{
	wxDateTime now = wxDateTime::Now();

	//Write System Log here.
	if( type == 1 ) {
		wxString sysinfo = wlssys.ErrMsg;
		if( !sysinfo.IsEmpty() ) {
			wxString crttime = now.Format(wxT("[%y-%m-%d %X]: [WARN]: "),wxDateTime::A_WST);
			//m_txtSystem->Clear();
			m_txtSystem->AppendText(crttime + m_threaddumpsvrname + sysinfo);
			m_txtSystem->AppendText(wxT("\n"));
		}
		wlssys.ErrMsg.Empty();
	} else {
		if( !m_diedsvrname.IsEmpty() ) {
			wxString crttime = now.Format(wxT("[%y-%m-%d %X]: [WARN]: "),wxDateTime::A_WST);
			//m_txtSystem->Clear();
			m_txtSystem->AppendText(crttime + m_diedsvrname );
			m_txtSystem->AppendText(wxT("\n"));
		}

		if( !m_jvmlowsvrname.IsEmpty() ) {
			wxString crttime = now.Format(wxT("[%y-%m-%d %X]: [WARN]: "),wxDateTime::A_WST);
			//m_txtSystem->Clear();
			m_txtSystem->AppendText(crttime + m_jvmlowsvrname );
			m_txtSystem->AppendText(wxT("\n"));
		}

		if( !m_jdbclowsvrname.IsEmpty() ) {
			wxString crttime = now.Format(wxT("[%y-%m-%d %X]: [WARN]: "),wxDateTime::A_WST);
			//m_txtSystem->Clear();
			m_txtSystem->AppendText(crttime + m_jdbclowsvrname);
			m_txtSystem->AppendText(wxT("\n"));
		}

		if( !m_thdlowsvrname.IsEmpty() ) {
			wxString crttime = now.Format(wxT("[%y-%m-%d %X]: [WARN]: "),wxDateTime::A_WST);
			//m_txtSystem->Clear();
			m_txtSystem->AppendText(crttime + m_thdlowsvrname);
			m_txtSystem->AppendText(wxT("\n"));
		}
	}

}
int WlsSpyPanel::SvrDataParser()
{
	WebLogicServer wlssvr;
	WebLogicJVM wlsjvm;
	WebLogicThread wlsthd;
	WebLogicJDBC wlsjdbc;

	wxXmlNode *child;
	wxString content;
	wxXmlDocument doc;

	wxString JDBCTag;
	wxString ThreadTag;

	wxString serverstate_list[]= {
		wxT("HEALTH_OK"),
		wxT("HEALTH_WARN"),
		wxT("HEALTH_CRITICAL"),
		wxT("HEALTH_FAILED"),
		wxT("")
	};
	try {
		wxStringInputStream stream( m_rcvdata );
		if( !doc.Load(stream) ) {
			return -1;
		}
		if (doc.GetRoot()->GetName() != wxT("MONITOR")) {
			return -1;
		}
	} catch (...) {
		return -1;
	}
	try {
		m_lastupdate = doc.GetRoot()->GetPropVal(wxT("Date"), wxT("0"));
	} catch (...) {
		return -1;
	}

	wlssvrarray.Empty();
	wlsjvmarray.Empty();
	wlsthdarray.Empty();
	wlsjdbcarray.Empty();

	child = doc.GetRoot()->GetChildren();

	while( child) {
		wxString nodename = child->GetName();
		if( nodename == wxT("ServerRuntime") ){
			wlssvr.ServerName = child->GetPropVal(wxT("serverName"), wxT("N/A"));
			//wlssvr.OSName = child->GetPropVal(wxT("OSName"),wxT("N/A"));
			//wlssvr.OSVersion = child->GetPropVal(wxT("OSVersion"), wxT("N/A"));
			wlssvr.PORT = child->GetPropVal(wxT("ListenPort"), wxT("N/A"));
			wlssvr.State = child->GetPropVal(wxT("State"), wxT("N/A"));
			wlssvr.HealthState = child->GetPropVal(wxT("HealthState"), wxT("N/A"));
			for ( int i = 0; !serverstate_list[i].IsEmpty(); i ++ ) {
				if( wlssvr.HealthState.Contains(serverstate_list[i]) ) {
					wlssvr.HealthState = serverstate_list[i];
				}
			}
			wlssvr.URL = child->GetPropVal(wxT("ListenAddress"), wxT("N/A"));
			wlssvrarray.Add( wlssvr );
		}

		if( nodename == wxT("JVMRuntime") ){
			wlsjvm.ServerName = child->GetPropVal(wxT("serverName"), wxT("N/A"));
			wlsjvm.Vendor = child->GetPropVal(wxT("JavaVendor"),wxT("N/A"));
			wlsjvm.Version = child->GetPropVal(wxT("JavaVersion"), wxT("N/A"));
			wlsjvm.FreeHeap = child->GetPropVal(wxT("HeapFreeCurrent"), wxT("N/A"));
			wlsjvm.CurrHeap = child->GetPropVal(wxT("HeapSizeCurrent"), wxT("N/A"));
			wlsjvm.HeapSizeMax = child->GetPropVal(wxT("HeapSizeMax"), wxT("N/A"));
			wlsjvm.FreePercent = child->GetPropVal(wxT("HeapFreePercent"), wxT("N/A")) + wxT("%");
			wlsjvmarray.Add( wlsjvm );
		}

		if( m_site.WlsVer.Contains(wxT("V8")) ) {
			ThreadTag = wxT("ExecuteQueueRuntime");
			if( nodename == ThreadTag ){
				wlsthd.ServerName = child->GetPropVal(wxT("serverName"), wxT("N/A"));
				wlsthd.IdleCount = child->GetPropVal(wxT("ExecuteThreadCurrentIdleCount"),wxT("N/A"));
				wlsthd.TotalCount = child->GetPropVal(wxT("ExecuteThreadTotalCount"), wxT("N/A"));
				wlsthd.ThroughPut = child->GetPropVal(wxT("ServicedRequestTotalCount"), wxT("N/A"));
				wlsthd.QueueLength = child->GetPropVal(wxT("PendingRequestCurrentCount"), wxT("N/A"));
				wxString quename = child->GetPropVal(wxT("Name"), wxT("N/A"));
				if( quename == wxT("weblogic.kernel.Default") || quename == wxT("default") ) 
					wlsthdarray.Add( wlsthd );
			}
		} else {
			ThreadTag = wxT("ThreadPoolRuntime");
			if( nodename == ThreadTag ){
				wlsthd.ServerName = child->GetPropVal(wxT("serverName"), wxT("N/A"));
				wlsthd.IdleCount = child->GetPropVal(wxT("ExecuteThreadIdleCount"),wxT("N/A"));
				wlsthd.TotalCount = child->GetPropVal(wxT("ExecuteThreadTotalCount"), wxT("N/A"));
				wlsthd.ThroughPut = child->GetPropVal(wxT("Throughput"), wxT("N/A"));
				wlsthd.QueueLength = child->GetPropVal(wxT("QueueLength"), wxT("N/A"));
				wlsthdarray.Add( wlsthd );
			}
		}

		if( m_site.WlsVer.Contains(wxT("V8")) )
			JDBCTag = wxT("JDBCConnectionPoolRuntime");
		else
			JDBCTag = wxT("JDBCServiceRuntime.JDBCDataSourceRuntimeMBeans");

		if( nodename == JDBCTag ){
			wlsjdbc.ServerName = child->GetPropVal(wxT("serverName"), wxT("N/A"));
			wlsjdbc.ActiveConnectionsCurrentCount = child->GetPropVal(wxT("ActiveConnectionsCurrentCount"),wxT("N/A"));
			wlsjdbc.ActiveConnectionsHighCount = child->GetPropVal(wxT("ActiveConnectionsHighCount"), wxT("N/A"));
			wlsjdbc.CurrCapacity = child->GetPropVal(wxT("CurrCapacity"), wxT("N/A"));
//			wlsjdbc.DeploymentState = child->GetPropVal(wxT("DeploymentState"), wxT("N/A"));
//			wlsjdbc.FailedReserveRequestCount = child->GetPropVal(wxT("FailedReserveRequestCount"), wxT("N/A"));
			wlsjdbc.LeakedConnectionCount = child->GetPropVal(wxT("LeakedConnectionCount"), wxT("N/A"));
			wlsjdbc.Name = child->GetPropVal(wxT("Name"), wxT("N/A"));
			wlsjdbc.State = child->GetPropVal(wxT("State"), wxT("N/A"));
			wlsjdbcarray.Add( wlsjdbc );
		}

		if( nodename == wxT("INITBUF") ){
			if( m_site.WlsVer.Contains(wxT("V8")) ) {
				wlsinitbuf.Activationtime = child->GetPropVal(wxT("ActivationTime"), wxT("N/A"));
			} else {
				wlsinitbuf.Activationtime = child->GetPropVal(wxT("Activationtime"), wxT("N/A"));
			}
			wlsinitbuf.AdminServerName = child->GetPropVal(wxT("AdminServerName"), wxT("N/A"));
			wlsinitbuf.Name = child->GetPropVal(wxT("Name"), wxT("N/A"));
			wlsinitbuf.DomainVersion = child->GetPropVal(wxT("DomainVersion"), wxT("N/A"));
			wlsinitbuf.GuardianEnabled = child->GetPropVal(wxT("GuardianEnabled"), wxT("N/A"));
			wlsinitbuf.JDKVendor = child->GetPropVal(wxT("JDKVendor"), wxT("N/A"));
			wlsinitbuf.JDKVersion = child->GetPropVal(wxT("JDKVersion"), wxT("N/A"));
			wlsinitbuf.OSName = child->GetPropVal(wxT("OSName"), wxT("N/A"));
			wlsinitbuf.OSVersion = child->GetPropVal(wxT("OSVersion"), wxT("N/A"));
			wlsinitbuf.ProductionModeEnabled = child->GetPropVal(wxT("ProductionModeEnabled"), wxT("N/A"));
			wlsinitbuf.RootDirectory = child->GetPropVal(wxT("RootDirectory"), wxT("N/A"));
			wlsinitbuf.ServerNum = child->GetPropVal(wxT("ServerNum"), wxT("N/A"));
			wlsinitbuf.AgentVersion = child->GetPropVal(wxT("AgentVersion"), wxT("N/A"));
		}
		if( nodename == wxT("SYSTEM") ){
			wlssys.ErrMsg = child->GetPropVal(wxT("errMsg"), wxT(""));
		}
		if( nodename == wxT("OSResource") ){
			wlssys.IdleCPU = child->GetPropVal(wxT("CPU"), wxT(""));
			wlssys.FreeMem = child->GetPropVal(wxT("MEM"), wxT(""));
		}
		child = child->GetNext();
	}

	AlarmSvrData( );
	return 1;

}

void WlsSpyPanel::AlarmSvrData( )
{
	WebLogicJVM wlsjvm;
	WebLogicThread wlsthd;
	WebLogicJDBC wlsjdbc;
	float rate = 0, setting;

	// JVM Action Judge
	for ( size_t i = 0; i < wlsjvmarray.GetCount(); i ++ ) {
		wlsjvm = wlsjvmarray.Item(i);
		if( ! m_wlsalarm.FreeHeap.IsEmpty() ){ //Need To Verify FreeHeapLow
			if( (float)wxAtoi(wlsjvm.FreePercent) < ((float)wxAtoi(m_wlsalarm.FreeHeap) / 100) )
				wlsjvmarray.Item(i).Flag |= JVMLOW;
				wlsjvmarray.Item(i).Flag |= COLOR;
				SetAlarmType( wlsjvmarray.Item(i).ServerName, JVMLOW );// To Alarm
		}
	}

	// Thread Action Judge
	for ( size_t i = 0; i < wlsthdarray.GetCount(); i ++ ) {
		wlsthd = wlsthdarray.Item(i);
		if( ! m_wlsalarm.IdleThread.IsEmpty() ){ //Need To Verify ThreadLow
			rate = (float)wxAtoi(wlsthd.IdleCount) / (float)wxAtoi(wlsthd.TotalCount); 
			setting = (float)wxAtoi(m_wlsalarm.IdleThread) / 100;
			if(  rate  < setting ) {
				wlsthdarray.Item(i).Flag |= THREADLOW;
				wlsthdarray.Item(i).Flag |= COLOR;
				SetAlarmType( wlsthdarray.Item(i).ServerName, THREADLOW );// To Alarm
			}
		}
	}

	// JDBC Action Judge
	for ( size_t i = 0; i < wlsjdbcarray.GetCount(); i ++ ) {
		wlsjdbc = wlsjdbcarray.Item(i);
		if( ! m_wlsalarm.IdleJDBC.IsEmpty() ){ //Need To Verify JDBC Low
			rate = (float)(wxAtoi(wlsjdbc.CurrCapacity) - wxAtoi(wlsjdbc.ActiveConnectionsCurrentCount) ) / 
				wxAtoi(wlsjdbc.CurrCapacity);
			setting = (float)wxAtoi(m_wlsalarm.IdleJDBC) / 100;
			if( rate < setting ) {
				wlsjdbcarray.Item(i).Flag |= JDBCLOW;
				wlsjdbcarray.Item(i).Flag |= COLOR;
				SetAlarmType( wlsjdbcarray.Item(i).ServerName, JDBCLOW );// To Alarm
			}
		}
	}

	return;

}

int WlsSpyPanel::DoAlarmAction()
{
	wxString alartmsg;

	if ( ! m_diedsvrname.IsEmpty() ) {
		m_diedsvrname += wxT(" Died!!!");
		//wxMessageBox(m_diedsvrname);
		alartmsg += m_diedsvrname;
	}
	if ( ! m_jvmlowsvrname.IsEmpty() ) {
		m_jvmlowsvrname += wxT(" JVM Heap Too Low!!!");
		//wxMessageBox(m_longbusysvrname);
		alartmsg += m_jvmlowsvrname;
	}
	if ( ! m_jdbclowsvrname.IsEmpty() ) {
		m_jdbclowsvrname += wxT(" Free JDBC Too Low!!!");
		//wxMessageBox(m_longidlesvrname);
		alartmsg += m_jdbclowsvrname;
	}
	if ( ! m_thdlowsvrname.IsEmpty() ) {
		m_thdlowsvrname += wxT(" Free Thread Too Low!!!");
		//wxMessageBox(m_longidlesvrname);
		alartmsg += m_thdlowsvrname;
	}

	if ( ! m_threaddumpsvrname.IsEmpty() ) {
		m_threaddumpsvrname += wxT(" Do ThreadDump !!!");
		//wxMessageBox(m_longidlesvrname);
	}


	if( m_wlsalarm.PlaySound == wxT("TRUE") && !alartmsg.empty() ) { //Alarm PlayMusic.
		alarmaction.PlayMusic();
	}

	if( m_wlsalarm.SMS == wxT("TRUE") && !alartmsg.empty() ) { //Alarm SendSMS.
		alarmaction.SendSMS(alartmsg);
	}

	if( m_wlsalarm.Email == wxT("TRUE") && !alartmsg.empty() ) { //Alarm Send EMail.
		alarmaction.SendMail(alartmsg);
	}

	if( m_wlsalarm.ThreadDump == wxT("TRUE") && !alartmsg.empty() ) { //Alarm Do ThreadDump
		SetUrgentAlarm();
	}

	UpdateLogWindow( 2 );

	//Initial those alarm messages.
	m_diedsvrname.Empty();	m_jvmlowsvrname.Empty();
	m_jdbclowsvrname.Empty(); m_thdlowsvrname.Empty();
	m_threaddumpsvrname.Empty(); m_xmldumpcontent.Empty();


	return 1;
}

int WlsSpyPanel::SetAlarmType( wxString svrname, int alarmtype )
{

	switch( alarmtype ) {
		case SVRDIED:
			if( !m_diedsvrname.Contains(svrname) )  {
				m_diedsvrname += wxT("[ ");
				m_diedsvrname += svrname;
				m_diedsvrname += wxT("] ");
			}
			break;
		case JVMLOW:
			if( !m_jvmlowsvrname.Contains(svrname) ) {
				m_jvmlowsvrname += wxT("[ ");
				m_jvmlowsvrname += svrname;
				m_jvmlowsvrname += wxT("] ");
			}
			break;
		case JDBCLOW:
			if( !m_jdbclowsvrname.Contains(svrname) )  {
				m_jdbclowsvrname += wxT("[ ");
				m_jdbclowsvrname += svrname;
				m_jdbclowsvrname += wxT("] ");
			}
			if( !m_threaddumpsvrname.Contains(svrname) ) {
				for ( size_t i = 0; i < wlssvrarray.GetCount(); i ++ ) {
					if( wlssvrarray.Item(i).ServerName == svrname ){
						wxString xmlbuf = wxString::Format( wxT("<Server name=\"%s\" url=\"%s:%s\" dumpCount=\"3\"/>"),
							wlssvrarray.Item(i).ServerName, wlssvrarray.Item(i).URL, wlssvrarray.Item(i).PORT);
						m_xmldumpcontent += xmlbuf;
						m_threaddumpsvrname += wxT("[ ");
						m_threaddumpsvrname += svrname;
						m_threaddumpsvrname += wxT("] ");
						//SetUrgentAlarm( xmlbuf );
						break;
					}
				}
				
			}
			break;

		case THREADLOW:
			if( !m_thdlowsvrname.Contains(svrname) )  {
				m_thdlowsvrname += wxT("[ ");
				m_thdlowsvrname += svrname;
				m_thdlowsvrname += wxT("] ");
			}
			if( !m_threaddumpsvrname.Contains(svrname) ) {
				for ( size_t i = 0; i < wlssvrarray.GetCount(); i ++ ) {
					if( wlssvrarray.Item(i).ServerName == svrname ){
						wxString xmlbuf = wxString::Format( wxT("<Server name=\"%s\" url=\"%s:%s\" dumpCount=\"2\" />"),
							wlssvrarray.Item(i).ServerName, wlssvrarray.Item(i).URL, wlssvrarray.Item(i).PORT);
						m_xmldumpcontent += xmlbuf;
						m_threaddumpsvrname += wxT("[ ");
						m_threaddumpsvrname += svrname;
						m_threaddumpsvrname += wxT("] ");
						//m_threaddumpxml.Empty();
					}
				}
			}
			break;

		default:
			break;
	}

	return 1;
}
int WlsSpyPanel::SetUrgentAlarm( )
{
	wxString xmlhead = wxT("<?xml version=\"1.0\" encoding=\"UTF-8\" ?><wlsagent>");
	wxString xmltail = wxT("</wlsagent>");
	wxString xmlbuffer = xmlhead + m_xmldumpcontent + xmltail;

	m_rcvdata = m_tuxsite.ActVsAgent(WLSDUMP, xmlbuffer);

	if( m_rcvdata == wxT("") ){
		if( m_tuxsite.TestConnect() == -1 ) {
			wxString sysinfo = wxT("Connection to Agent is Broken! Re-Connect Please!");
			m_txtSystem->Clear();
			m_txtSystem->AppendText(sysinfo);
			m_timer.Stop();
			m_tuxsite.Close();
			m_IsStart = false;
			m_btnControl->SetLabel(wxT("Start"));
			m_txtInterval->Enable(true);
		}
	}else {
		if( SvrDataParser( ) > 0 ) {
			UpdateLogWindow( 1 );
		}
	}

	return 1;
}

#include "wx/arrimpl.cpp"
//WX_DEFINE_OBJARRAY(WebLogicServerArray);
//WX_DEFINE_OBJARRAY(WebLogicJVMArray);
//WX_DEFINE_OBJARRAY(WebLogicThreadArray);
//WX_DEFINE_OBJARRAY(WebLogicJDBCArray);
